package com.devmar
{
	import mx.core.Application;
	import com.salesforce.Connection;
	import mx.collections.ArrayCollection;
	import com.salesforce.AsyncResponder;
	import com.salesforce.results.QueryResult;
	import com.salesforce.objects.SObject;
	import mx.controls.Alert;
	import mx.charts.ColumnChart;
	import mx.utils.ArrayUtil;
	import mx.controls.Text;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import mx.controls.TextInput;
	import mx.effects.Parallel;

	public class IncubatorBoardAppCode extends Application
	{
		[Bindable]
		public var columnchart1:ColumnChart;
		[Bindable]
		public var label1:Text;
		
		
		private var apex:Connection = new Connection();
		private static var PUBLIC_PARTNER_OFFERING_SOQL:String = "Select Id, ScreenShot_URI__c, Public__c, Name, Logo__c, Logo_URI__c, " +
			"Certified__c, Category__c, CampaignIdLearnMore__c, CampaignIdInstall__c, CampaignIdDownload__c, CampaignIdDemo__c, " +
			"CampaignIdActualDemo__c, AverageRating__c From Partner_Offering__c Where Public__c = true and (CampaignIdDemo__c != null and " +
			"CampaignIdActualDemo__c != null and CampaignIdInstall__c != null and CampaignIdLearnMore__c != null)";
		
		private var publicPartnerOfferings:QueryResult;
		
		[Embed(source="assets/promo.swf")]
		[Bindable]
		public var imgCls:Class;
		//[Bindable]
		//public var publicOfferingInstallData:Object = new Object();
		
		[Bindable]
		public var currentOfferingData:ArrayCollection;
		
		private var currentOffering:SObject = null;
		private var currentGraphData:GraphData = null;
		//public var columnchart1:ColumnChart;
		public var hideEffects:Parallel;
		public var showEffects:Parallel;
		
		[Bindable]
     	public var expenses:ArrayCollection = new ArrayCollection([
        	{Month:"Jan", Profit:2000, Expenses:1500, Amount:450},
        	{Month:"Feb", Profit:1000, Expenses:200, Amount:600},
        	{Month:"Mar", Profit:1500, Expenses:500, Amount:300}
     		]);
     	private var loginResponder:AsyncResponder;
     	public var txtUsername:TextInput;
     	public var txtPassword:TextInput;
     	
     	protected function initConn():void {
     		apex.serverUrl = "https://www.salesforce.com/services/Soap/u/9.0";
     		loginResponder = new AsyncResponder(handleLogin, handleFault);
     	}
     	public function doLogin():void {
     		apex.loginWithCredentials(txtUsername.text, txtPassword.text, loginResponder);
     	}
     	private function handleLogin(result:Object):void {
     		currentState = "";
     		columnchart1.setStyle("hideEffect", hideEffects);
     		columnchart1.setStyle("showEffect", showEffects);
     		application.callLater(getPublicPartnerOfferings);
     	}
     	private function handleFault(fault:Object):void {
     		Alert.show(fault.toString());
     	}
     	private function getPublicPartnerOfferings():void {
     		var resp:AsyncResponder = new AsyncResponder(handlePublicPartnerOfferings, handleFault);
     		apex.query(PUBLIC_PARTNER_OFFERING_SOQL, resp);
     	}
     	private function handlePublicPartnerOfferings(results:QueryResult):void {
      		publicPartnerOfferings = results;
      		currentOffering = publicPartnerOfferings.records[0];
      		startTimer();
      		//refreshDataBuckets();
     	}
     	private function startTimer():void {
      		var t:Timer = new Timer(7000);
     		t.addEventListener(TimerEvent.TIMER, handleTimerTick);
     		currentGraphData = null;
     		refreshDataBucket();
     		t.start();
    	}
     	private function refreshDataBucket():void {
 			//Get the Test Drive numbers
 			var soql:String = "Select Count() From CampaignMember Where (CampaignId = '" + currentOffering.CampaignIdDemo__c + "' or CampaignId = '" + currentOffering.CampaignIdActualDemo__c + "')";
 			apex.query(soql, new AsyncResponder(saveData, handleFault, { partnerOffering:currentOffering, category:"Total", dataBucket:"demoData" }));
 			apex.query(soql + " and CreatedDate = LAST_N_DAYS:30",new AsyncResponder(saveData, handleFault, {partnerOffering:currentOffering, category:"Month", dataBucket:"demoData"}));
 			apex.query(soql + " and CreatedDate = TODAY", new AsyncResponder(saveData, handleFault, {partnerOffering:currentOffering, category:"Today", dataBucket:"demoData"}));
 			
 			//Get the install numbers
 			soql = "Select Count() From CampaignMember Where (CampaignId = '" + currentOffering.CampaignIdInstall__c + "')";
 			apex.query(soql, new AsyncResponder(saveData, handleFault, { partnerOffering:currentOffering, category:"Total", dataBucket:"installData" }));
 			apex.query(soql + " and CreatedDate = LAST_N_DAYS:30",new AsyncResponder(saveData, handleFault, {partnerOffering:currentOffering, category:"Month", dataBucket:"installData"}));
 			apex.query(soql + " and CreatedDate = TODAY", new AsyncResponder(saveData, handleFault, {partnerOffering:currentOffering, category:"Today", dataBucket:"installData"}));
 			
 			//Get the learn more
 			soql = "Select Count() From CampaignMember Where (CampaignId = '" + currentOffering.CampaignIdLearnMore__c + "')";
 			apex.query(soql, new AsyncResponder(saveData, handleFault, { partnerOffering:currentOffering, category:"Total", dataBucket:"learnMoreData" }));
 			apex.query(soql + " and CreatedDate = LAST_N_DAYS:30",new AsyncResponder(saveData, handleFault, {partnerOffering:currentOffering, category:"Month", dataBucket:"learnMoreData"}));
 			apex.query(soql + " and CreatedDate = TODAY", new AsyncResponder(saveData, handleFault, {partnerOffering:currentOffering, category:"Today", dataBucket:"learnMoreData"}));
     	}
     	private function saveData(result:QueryResult):void {
     		var po:SObject = result.context.partnerOffering as SObject;
     		var cat:String = result.context.category as String;
     		var dataBucket:String = result.context.dataBucket as String;
     		var poId:String = po.Id as String
     		if (currentGraphData != null) {
     			if (dataBucket == "installData") {
     				currentGraphData.addInstallData(cat, result.size);
     			} else if (dataBucket == "demoData") {
     				currentGraphData.addDemoData(cat, result.size);
     			} else {
     				currentGraphData.addLearnMoreData(cat, result.size);
     			}
     		} else {
     			currentGraphData = new GraphData();
     			currentGraphData.offeringRecord = po;
     			if (dataBucket == "installData") {
     				currentGraphData.addInstallData(cat, result.size);
     			} else {
     				currentGraphData.addDemoData(cat, result.size);
     			}
     		}
   			currentOffering = po;
   			if (!columnchart1.visible) {
	   			columnchart1.visible = true;
	   		}
     	}
     	public function changeDisplayedOffering():void {
     		currentOfferingData = currentGraphData.partnerOfferingData;
     		label1.text = currentOffering.Name;
     	}
     	private function handleTimerTick(event:TimerEvent):void {
     		columnchart1.visible = false;
     	}
     	public function finishTimer(event:Object):void {
     		var keyFound:Boolean = false;
     		var nextKey:String = null;
     		var currentOfferingId:String = currentOffering.Id as String;
     		currentGraphData = null;
     		//need to cycle the offering data
     		for (var i:int=0;i<publicPartnerOfferings.records.length;i++) {
     			if (keyFound) {
     				currentOffering = publicPartnerOfferings.records[i] as SObject;
     				refreshDataBucket();
     				break;
     			} else {
     				if (publicPartnerOfferings.records[i].Id == currentOfferingId) {
     					keyFound = true;
     				}
     			}
     		}
     		if (!keyFound) {
     			currentOffering = publicPartnerOfferings.records[0];
     			refreshDataBucket();
     		}
     	}
	}
}